package com.doubao.auth.client;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.util.Map;

@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "sms.jumdata")
public class JumdataSmsClient {

    private String appCode;
    private String templateId;
    private String url = "https://smssend.apistore.huaweicloud.com/sms/send";

    private final RestTemplate restTemplate;

    public JumdataSmsClient(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 发送短信验证码
     * @param phoneNumber 接收验证码的手机号
     * @param code 验证码
     * @return 是否发送成功
     */
    public boolean sendVerificationCode(String phoneNumber, String code) {
        try {
            if (appCode == null || appCode.isEmpty()) {
                log.error("AppCode为空，无法发送短信");
                return false;
            }

            if (templateId == null || templateId.isEmpty()) {
                log.error("TemplateId为空，无法发送短信");
                return false;
            }

            // 设置短信有效时间为60秒
            String validityTime = "60";

            // 直接使用特殊字符替换竖线
            String values = code + "|" + validityTime;

            // 设置请求头，包含AppCode认证
            HttpHeaders headers = new HttpHeaders();
            headers.set("X-Apig-AppCode", appCode);
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            // 构建URL
            String requestUrl = url +
                    "?receive=" + phoneNumber +
                    "&templateId=" + templateId +
                    "&values=" + values +
                    "&tag=register";

            log.debug("聚智数美短信请求URL: {}", requestUrl);

            // 发送POST请求
            ResponseEntity<Map> responseEntity = restTemplate.postForEntity(
                    requestUrl,
                    new HttpEntity<>(null, headers),
                    Map.class
            );

            Map<String, Object> response = responseEntity.getBody();
            log.info("聚智数美短信发送响应: {}", response);

            // 检查发送结果
            if (response != null) {
                // 根据错误信息判断是否发送成功
                if (Boolean.TRUE.equals(response.get("success"))) {
                    return true;
                }

                // 记录详细的错误信息
                String errorMsg = response.getOrDefault("msg", "未知错误").toString();
                log.error("聚智数美短信发送失败: {}", errorMsg);
            }

            return false;
        } catch (Exception e) {
            log.error("发送聚智数美短信验证码异常", e);
            return false;
        }
    }
}